<template>
  <div
      id='previewReport'
      v-loading='loading'
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
  >
    <div id='img'></div>
    <el-button
        type='primary'
        style='position: absolute;top: 10px;right: 10px'
        size='large'
        @click='exportToPDF'
    >
      导出PDF
    </el-button>
    <div v-for='(item, index) in projectDetailData'>
      <div class='dividerText'>
        <el-divider>{{item.basic_info[0]['项目名称']}}--{{item.week}}</el-divider>
      </div>

      <div class="baseInfo marT">
        <el-divider content-position="left">项目基础信息</el-divider>
        <el-table
            :border="true"
            :header-cell-style="{ background: '#42b1e8' }"
            :data="item.basic_info"
            style="width: 100%"
        >
          <el-table-column
              :label="column"
              align="center"
              v-for="column in item.basic_info && item.basic_info.length ? Object.keys(item.basic_info[0]) : []"
              :key="column"
          >
            <template slot-scope="scope">
              <div>{{ item.basic_info[scope.$index][column] }}</div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="total-condition marT">
        <el-divider content-position="left">项目总体状况</el-divider>
        <el-card shadow="always" class="flexing">
          <div class="left">
            <el-alert
                v-html="
                  item.project_total_condition
                    ? textAreaTo(item.project_total_condition)
                    : '暂无内容'
                "
                type="error"
                effect="dark"
                :closable="false"
            >
            </el-alert>
          </div>
          <div class="right">
            <label for="levels" style="margin: auto 15px">风险等级:</label>
            <template>
                <span v-if="item.risk_self_assessment === 1" class="low"
                >低风险</span
                >
              <span
                  v-else-if="item.risk_self_assessment === 2"
                  class="middle"
              >中风险</span
              >
              <span v-else class="high">高风险</span>
            </template>
          </div>
        </el-card>
      </div>

      <div class="projectStatus">
        <el-divider content-position="left">项目状况</el-divider>
        <el-table
            :border="true"
            :header-cell-style="{ background: '#42b1e8' }"
            :data="item.project_condition"
            style="width: 100%"
            :cell-style="backFun"
        >
          <el-table-column label="分类" align="center">
            <template slot-scope="scope">
              <div>
                {{ scope.row.risk_type }}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="风险等级" align="center">
            <template slot-scope="scope">
              <div v-if="typeof scope.row.risk_level == 'string'">
                {{ scope.row.risk_level }}
              </div>
              <div v-else>
                <div v-for="(v, k) in scope.row.risk_level" :key="k">
                  <span> {{ k }}</span> :
                  <span v-if="v === '低风险'" class="low"> {{ v }}</span>
                  <span v-else-if="v === '中风险'" class="middle">
                      {{ v }}
                    </span>
                  <span v-else-if="v === '高风险'" class="high">
                      {{ v }}
                    </span>
                  <span v-else> {{ v }} </span>  
                </div>
              </div>
              <!-- </div> -->
            </template>
          </el-table-column>

          <el-table-column label="风险责任人" align="center">
            <template slot-scope="scope">
              <div>
                {{ scope.row.risk_owner }}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="风险原因" align="center">
            <template slot-scope="scope">
              <div v-if="typeof scope.row.risk_level == 'string'">
                {{ scope.row.risk_level }}
              </div>
              <div v-else>
                <div v-for="(v, k) in scope.row.risk_reason" :key="k">
                  {{ k }} :
                  {{ v }}
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="风险计划解决时间" align="center">
            <template slot-scope="scope">
              <div>
                {{ scope.row.risk_solution_time }}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="风险解决方案" align="center">
            <template slot-scope="scope">
              <div
                  v-html="scope.row.risk_handle_progress"
                  style="
                    text-align: left;
                    white-space: pre-wrap;
                    word-wrap: break-word;
                    word-break: break-all;
                  "
              ></div>
            </template>
          </el-table-column>

          <el-table-column
              label="风险解决层级"
              align="center"
          >
            <template slot-scope="scope">
              <div>
                <span v-if="scope.row.risk_solution_level === '1'">项目组内解决</span>
                <span v-if="scope.row.risk_solution_level === '2'">事业部依赖</span>
                <span v-if="scope.row.risk_solution_level === '3'">事业群依赖</span>
                <span v-if="scope.row.risk_solution_level === '4'">客户部依赖</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="high-light">
        <el-divider content-position="left">风险HighLight</el-divider>
        <el-table
            :border="true"
            :header-cell-style="{background:'#42b1e8'}"
            :data="item.risk_highlight"
            style="width: 100%"
            :cell-style="backFun"
        >
          <el-table-column
              label="Top级别"
              align="center"
          >
            <template slot-scope="scope">
              <div>
                <span v-if="scope.row.top_level === '1'">Top1</span>
                <span v-if="scope.row.top_level === '2'">Top2</span>
                <span v-if="scope.row.top_level === '3'">Top3</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
              label="风险描述"
              align="center"
          >
            <template slot-scope="scope">
              <div v-html="scope.row.risk" />
            </template>
          </el-table-column>

          <el-table-column
              label="风险责任人"
              align="center"
          >
            <template slot-scope="scope">
              <div>
                {{ generate(scope.row.risk_owner).join(',') }}
              </div>
            </template>
          </el-table-column>


          <el-table-column
              label="解决方案"
              align="center"
          >
            <template slot-scope="scope">
              <div v-html="scope.row.doc" />
            </template>
          </el-table-column>

          <el-table-column
              label="解决时间"
              align="center"
          >
            <template slot-scope="scope">
              <div>
                {{ scope.row.time }}
              </div>
            </template>
          </el-table-column>

          <el-table-column
              label="解决层级"
              align="center"
          >
            <template slot-scope="scope">
              <div>
                <div v-if="scope.row.level === '1'">项目组内解决</div>
                <div v-if="scope.row.level === '2'">事业部依赖</div>
                <div v-if="scope.row.level === '3'">事业群依赖</div>
                <div v-if="scope.row.level === '4'">客户部依赖</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column
              label="风险状态"
              align="center"
          >
            <template slot-scope="scope">
              <div>
                <div v-if="scope.row.status==='1'">关闭</div>
                <div v-if="scope.row.status==='2'">非关闭</div>
              </div>
            </template>
          </el-table-column>

        </el-table>
      </div>

      <div class="now">
        <el-divider content-position="left">本周主要成果</el-divider>
        <el-alert
            type="success"
            :closable="false"
            v-html="
              item.current_week_outcome
                ? textAreaTo(item.current_week_outcome)
                : '暂无内容'
            "
        >
        </el-alert>
      </div>

      <div class="next">
        <el-divider content-position="left">下周工作计划</el-divider>
        <el-alert
            type="success"
            :closable="false"
            v-html="
              item.next_week_plan
                ? textAreaTo(item.next_week_plan)
                : '暂无内容'
            "
        >
        </el-alert>
      </div>

      <div class="file">
        <el-divider content-position="left">周报附件</el-divider>
        <ul>
          <li v-for="(file, index) in item.file_list" :key="index">
            <el-button @click="downloadSelection(file)">
              {{ file }}
            </el-button>
          </li>
        </ul>
      </div>

      <div class="review">
        <el-divider content-position="left">AM评审</el-divider>
        <el-alert
            type="success"
            :closable="false"
            v-html="item.review ? textAreaTo(item.review) : '暂无内容'"
        >
        </el-alert>
      </div>

<!--      <div class="selfCheck">-->
<!--        <el-divider content-position="left">项目自检</el-divider>-->
<!--        <template >-->
<!--          <div style="margin-bottom: 10px; color:red">-->
<!--            {{item.check_num}}-->
<!--          </div>-->
<!--        </template>-->
<!--        <el-table-->
<!--            :data="item.check"-->
<!--            border-->
<!--            :header-cell-style="{ background: '#42B1E8' }"-->
<!--            style="margin-top: 20px"-->
<!--        >-->
<!--          <el-table-column property="num" label="编号" width="50" align="center">-->
<!--            <template slot-scope="scope">-->
<!--              <div>{{ tableArr1[scope.$index]}}</div>-->
<!--            </template>-->
<!--          </el-table-column>-->

<!--          <el-table-column-->
<!--              label="检查项"-->
<!--              width="550"-->
<!--              align="center"-->
<!--          >-->
<!--            <template slot-scope="scope">-->
<!--              <div>{{ tableArr2[scope.row[0]] }}</div>-->
<!--            </template>-->
<!--          </el-table-column>-->

<!--          <el-table-column-->
<!--              label="结果"-->
<!--              width="150"-->
<!--              align="center"-->
<!--          >-->
<!--            <template slot-scope="scope">-->
<!--              <div>-->
<!--                {{scope.row[1].result}}-->
<!--              </div>-->
<!--            </template>-->
<!--          </el-table-column>-->

<!--          <el-table-column-->
<!--              label="说明"-->
<!--              width="300"-->
<!--              align="center"-->
<!--          >-->
<!--            <template slot-scope="scope">-->
<!--              <div>-->
<!--                {{scope.row[1].explain}}-->
<!--              </div>-->
<!--            </template>-->
<!--          </el-table-column>-->

<!--          <el-table-column-->
<!--              label="对策"-->
<!--              width="300"-->
<!--              align="center"-->
<!--          >-->
<!--            <template slot-scope="scope">-->
<!--              <div>-->
<!--                {{ scope.row[1].countermeasure }}-->
<!--              </div>-->
<!--            </template>-->
<!--          </el-table-column>-->

<!--          <el-table-column label="解决时间" align="center" width="284">-->
<!--            <template slot-scope="scope">-->
<!--              <div>-->
<!--                {{ scope.row[1].fix_time }}-->
<!--              </div>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--        </el-table>-->
<!--      </div>-->
    </div>

  </div>
</template>

<script>
import { mapState } from 'vuex';
import http from '@/views/sys/axios'


export default {
  name: 'previewReport',
  computed: {
    ...mapState({
      dispose: state => state.conditions.dispose
    })
  },
  props: ['multipleSelection'],
  data() {
    return {
      projectDetailData: [],
      tableArr1:[1,2,3,4,5,6,7,8],
      tableArr2:[
        'PM是否按时组织实施了项目周会',
        'PM是否在项目管理看板更新了进度，成本等相关KPI，对项目进度，商务，成本等方面的风险做了说明与判断',
        '架构师，研发Leader是否在项目管理看板更新了技术领域KPI，对项目技术风险做了说明与判断',
        '测试Leader是否在项目管理看板更新了测试相关KPI，对项目质量风险做了说明与判断',
        '各领域负责人是否在周会上确认了当前阶段需要达成KPI目标和交付件的进展，并识别风险与问题向PM汇报，给出依赖与对策或建议',
        'PM是否基于项目管理看板填写结果，对当前阶段点各领域KPI目标的状况进行了跟踪与确认',
        'PM是否确认各领域的风险和课题，以及对策和依赖。协助各领域推动解决风险和课题',
        '是否按照阶段点计划，在周会上跟踪了阶段点实施的必要动作（建立任务，领域自检，问题对策与跟踪等）',
      ],
      tableArr3:[],
      loading: true,
    }
  },
  methods: {
    getProjectDetail(projectIdList) {
      const { weeks, deliver_center, project_level, levels } = this.dispose
      const query = {}
      if (weeks) {
        query.week = weeks
      }
      if (deliver_center.length) {
        query.project__core__in = deliver_center
      }
      if (project_level) {
        query.project__project_level = project_level
      }
      if (levels.length) {
        query.risk_self_assessment__in = levels
      }
      const data = {
        report_id: projectIdList,
        query,
        isReportIDList: false
      }
      return http.post(`/api/report/project/weekly/detail`, data);
    },
    getSelectedReportDetail(multipleSelection) {
      const data = {
        report_id: multipleSelection,
        isReportIDList: true,
      }
      return http.post(`/api/report/project/weekly/detail`, data);
    },
    async initialProjectDetail() {
      if (this.multipleSelection.length) {
        const { code, data } = await this.getSelectedReportDetail(this.multipleSelection)
        this.projectDetailData = data
        this.loading = false
      } else {
        const tmpvalueList = JSON.parse(localStorage.getItem('tmpvalueList'))
        const { code, data } = await this.getProjectDetail(tmpvalueList && tmpvalueList.length ? tmpvalueList: this.dispose.oriProjectIDList.map(item => item[2]))
        this.projectDetailData = data
        this.loading = false
      }
    },
    textAreaTo(str) {
      let regs = new RegExp('\r', 'g');
      let reg = new RegExp('\n', 'g');
      str = str.replace(reg, '<br/>');
      str = str.replace(regs, '<br/>');
      return str;
    },
    backFun({ row, columnIndex }) {
      if (row.hasOwnProperty('risk_self_assessment')) {
        if (columnIndex === 3) {
          if (row.risk_self_assessment === 1) {
            return 'background: #67c23a;color: #fff';
          } else if (row.risk_self_assessment === 2) {
            return 'background: #e6a23c;color: #fff';
          } else if (row.risk_self_assessment === 3) {
            return 'background: #e4393c;color: #fff';
          }
        }
      } else {
        if (columnIndex === 1) {
          if (row.risk_level && row.risk_level === '低风险') {
            return 'background: #67c23a;color: #fff';
          } else if (row.risk_level && row.risk_level === '中风险') {
            return 'background: #e6a23c;color: #fff';
          } else if (row.risk_level && row.risk_level === '高风险') {
            return 'background: #e4393c;color: #fff';
          }
        }
      }
    },
    generate(arr) {
      if(arr) {
        const list = arr.map(item => item.label)
        return list
      } else {
        return []
      }
    },
    downloadSelection(name) {
      this.loadingbut = true;
      this.loadingbuttext = '保存中...';
      http
          .get(
              `${process.env.VUE_APP_KANBAN_HOST}/api/report/project/weekly/report/file?file_name=${name}&report_id=${this.currentId}`,
              { responseType: 'blob' }
          )
          .then((res) => {
            const { data, status } = res;
            if (status === 200) {
              let blob = new Blob([data], { type: 'application/octet-stream' });
              const link = document.createElement('a');
              link.style.display = 'none';
              link.href = URL.createObjectURL(blob);
              link.setAttribute('download', name);
              document.body.appendChild(link);
              link.click();
              URL.revokeObjectURL(link.href);
              document.body.removeChild(link);
              this.loadingbut = false;
              this.loadingbuttext = '下载';
            } else {
              this.$message.error('下载出错了!');
            }
          })
          .catch((err) => {
            const { data } = err;

            if (data) {
              let blob = new Blob([data], { type: 'application/octet-stream' });
              const link = document.createElement('a');
              link.style.display = 'none';
              link.href = URL.createObjectURL(blob);
              link.setAttribute('download', name);
              document.body.appendChild(link);
              link.click();
              URL.revokeObjectURL(link.href);
              document.body.removeChild(link);
            } else {
              this.$message.error('下载出错了!');
            }
          });
    },
    async exportToPDF() {
      const data = {
        report_id: this.projectDetailData.map(item => item.id),
        isReportIDList: true,
      }
      this.loading = true
      http.post(`/api/report/project/weekly/download_report_pdf`, data, { responseType: 'blob' })
      .then(res => {
        const { data } = res;
        if (data) {
          let blob = new Blob([data], { type: 'application/pdf' });
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = URL.createObjectURL(blob);
          link.setAttribute('download', '周报预览.pdf');
          document.body.appendChild(link);
          link.click();
          URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
          this.$message.success('导出成功!');
        } else {
          this.$message.error('下载出错了!');
        }
        this.loading = false
      })
      .catch(err => {
        const { data } = err;
        if (data) {
          let blob = new Blob([data], { type: 'application/pdf' });
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = URL.createObjectURL(blob);
          link.setAttribute('download', '周报预览.pdf');
          document.body.appendChild(link);
          link.click();
          URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
          this.$message.success('导出成功!');
        } else {
          this.$message.error('下载出错了!');
        }
        this.loading = false
      })

    },
  },

  mounted() {
    this.initialProjectDetail()
  }
};
</script>

<style scoped>
  #previewReport {
    padding: 32px;
    background-color: rgb(240, 242, 245);
    position: relative;
    overflow-x: hidden;
    overflow-y: scroll;
    height: 80vh;
  }

  /deep/ .dividerText .el-divider__text {
    color: #ffffff;
    font-size: 20px;
    font-weight: 600;
    background-color: red!important;
    padding: 6px 16px;
  }

  .marT {
    margin-top: 20px;
  }
  .high {
    color: #e4393c;
  }
  .middle {
    color: #e6a23c;
  }
  .low {
    color: #67c23a;
  }

</style>
